package tencent

import (
	"encoding/json"
	"log/slog"
	"strings"

	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111" // 引入sms
)

type SmsSvc struct {
	Region    string
	SecretId  string
	SecretKey string
	SdkAppId  string
	client    *sms.Client
}

func (svc *SmsSvc) GetClient() (*sms.Client, error) {
	if svc.client == nil {
		credential := common.NewCredential(svc.SecretId, svc.SecretKey)
		cpf := profile.NewClientProfile()
		cpf.HttpProfile.Endpoint = "sms.tencentcloudapi.com"
		client, err := sms.NewClient(credential, svc.Region, cpf)
		if err != nil {
			slog.Error(err.Error())
			return nil, err
		}
		svc.client = client
	}
	return svc.client, nil
}

func (svc *SmsSvc) Send(signName, phoneNumber string, templateId string, params []string) error {
	request := sms.NewSendSmsRequest()
	request.SmsSdkAppId = common.StringPtr(svc.SdkAppId)
	request.SignName = common.StringPtr(signName)
	request.TemplateId = common.StringPtr(templateId)
	request.TemplateParamSet = common.StringPtrs(params)
	if !strings.HasPrefix(phoneNumber, "+") {
		phoneNumber = "+86" + phoneNumber
	}
	request.PhoneNumberSet = common.StringPtrs([]string{phoneNumber})

	client, err := svc.GetClient()
	if err != nil {
		slog.Error(err.Error())
		return err
	}
	response, err := client.SendSms(request)
	if err != nil {
		slog.Error(err.Error())
		return err
	}

	// 打印返回的json字符串
	b, _ := json.Marshal(response.Response)
	slog.Debug(string(b))

	return nil
}
